package com.sdkj.dspservice.modules.analysis.timer;

import com.sdkj.dspservice.common.utils.RedisUtils;
import com.sdkj.dspservice.modules.analysis.entity.PageAnalysis;
import com.sdkj.dspservice.modules.analysis.entity.PageParamAnalysis;
import com.sdkj.dspservice.modules.analysis.service.PageAnalysisService;
import org.apache.shiro.util.ThreadContext;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 需求模块定时器任务
 */
@Configuration
@EnableScheduling   // 2.开启定时任务
@RestController
@RequestMapping(value = "analysisTimer")
public class AnalysisTimer {

    @Autowired
    private PageAnalysisService pageAnalysisService;
    @Autowired
    private RedisTemplate redisTemplate;

    static DefaultWebSecurityManager manager = new DefaultWebSecurityManager();

    /**
     * 每天服务器的15点（中国时间23点），获取包含本月的3个自然月的url的domain+path
     * @throws SQLException
     * @throws InterruptedException
     */
    @Scheduled(cron = "0 0 15 * * ?")
    private void listAutoCompleteUrl() {
//    @RequestMapping(value = "listAutoCompleteUrl")
//    public void listAutoCompleteUrl() {
        ThreadContext.bind(manager);
        PageAnalysis pageAnalysis = new PageParamAnalysis();
        // 插入日期，日期为，例：当前时间2021-01-xx时，2020-11-1至当前时间
        // 改为只查一个月
        String startDate = LocalDate.now().minusDays(30).format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        pageAnalysis.setStartDate(startDate);
        pageAnalysis.setEndDate(LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")));
        List<String> urlList = pageAnalysisService.listUrl(pageAnalysis);
        // 存入redis
        if(urlList != null && !urlList.isEmpty()){
            RedisUtils redisUtils = new RedisUtils(redisTemplate);
            redisUtils.setObject(RedisUtils.ANALYSIS_MODULE_AUTO_COMPLETE_URL_LIST, urlList);
        }
    }
}